package com.sx.mvvmlibs.http

import android.util.Log
import com.blankj.utilcode.util.BusUtils
import com.sx.mvvmlibs.http.impl.IBaseResponse
import retrofit2.HttpException

/**
 * @Author: YY
 * @Date: 2022/1/12
 * @Description: 处理Http请求结果
 */
object HttpProcessor {

    const val notHttpException = -100
    const val entityNullable = -1
    const val entityCodeNullable = -2

    /**
     * 处理结果
     */
    fun <T> handleResult(
        entity: IBaseResponse<T?>?,
        onSuccess: (() -> Unit)? = null,
        onResult: ((t: T) -> Unit),
        onFailed: ((code: Int, msg: String?) -> Unit)? = null
    ) {
        // 防止实体为 null
        if (entity == null) {
            onFailed?.invoke(entityNullable, "实体为 null")
            return
        }
        val code = entity.code()
        val msg = entity.msg()

        // 防止状态码为 null
        if (code == null) {
            onFailed?.invoke(entityCodeNullable, "实体状态码为 null")
            return
        }

        // 请求成功
        if (code == ResultEnum.SUCCESS.code) {
            // 回调成功
            onSuccess?.invoke()
            // 实体不为 null 才有价值
            entity.data()?.let { onResult.invoke(it) }
        } else {
            if (code == ResultEnum.UNAUTHORIZED.code) {

            }
            // 失败了
            onFailed?.invoke(code, msg)
        }
    }

    /**
     * 处理异常
     */
    fun handleException(
        e: Exception,
        onFailed: (code: Int, msg: String?) -> Unit
    ) {
        return if (e is HttpException) {
            onFailed(e.code(), e.message())
        } else {
            val log = Log.getStackTraceString(e)
            onFailed(
                notHttpException,
                "网络请求发生错误，但错误不是 HttpException, 具体错误是\n${log.ifEmpty { e.message }}"
            )
        }
    }
}